package handler

import (
	"fmt"
	"go_study/entity"
	"go_study/redis"
	"go_study/sql_op"
	"net/http"

	"github.com/gin-gonic/gin"
)

// 处理登陆请求
func LoginHandler(ctx *gin.Context) {
	orm := sql_op.GetOrm()
	rdb := redis.GetRDB()

	//获取前端传参
	name := ctx.PostForm("name")
	password := ctx.PostForm("password")

	var user entity.User
	var hasName bool

	user, hasName = rdb.GetRedis(name)
	if !hasName { //redis中没有找到
		//数据库查找，检验该用户名是否存在
		user, hasName = orm.SelectByName(name)
	}

	var status string
	if !hasName { //用户名不存在
		fmt.Println("用户名不存在")
		status = "用户名不存在"
	} else { //用户名存在
		if user.GetPassword() == password { //密码校验成功
			rdb.SetRedis(name, user, 30) //登陆成功后将信息存入redis

			status = "登陆成功"
		} else { //密码校验失败
			status = "登陆失败，密码错误"
		}

	}
	//响应
	ctx.JSON(http.StatusOK, gin.H{
		"status": status,
	})
}

//git config --global --add safe.directory /usr/local/Homebrew/Library/Taps/homebrew/homebrew-core
//git config --global --add safe.directory /usr/local/Homebrew/Library/Taps/homebrew/homebrew-cask
